﻿using AutoMapper;
using Model.Entitys;
using Shop.Interface.Menu;
using Shop.Interface.Repository;
using Shop.Models.Dto.Menu;
using Shop.Services.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Shop.Services
{
    public class MenuService : IMenuService
    {
        private IBaseRepository _baseRepository;
        private readonly IMapper _mapper;
        public MenuService(IBaseRepository baseRepository, IMapper mapper)
        {
            _baseRepository= baseRepository;
            _mapper= mapper;
        }
        public async Task<bool> Add(MenuAdd req, string userId)
        {
            Menu info = _mapper.Map<Menu>(req);
            info.Id = Guid.NewGuid().ToString();
            info.CreateUserId= userId;
            info.CreateDate=DateTime.Now;
            info.IsDeleted= false;
            return await _baseRepository.Db.Insertable(info).ExecuteCommandAsync()>0;
        }

        public async Task<bool> BathDelete(string[] ids)
        {
            return await _baseRepository.BatchDelete<Menu>(ids);
        }

        public async Task<bool> Delete(string id)
        {
            return await _baseRepository.DeleteById<Menu>(id);
        }

        public async Task<bool> Edit(MenuEdit req, string userId)
        {
            var info = _baseRepository.Db.Queryable<Menu>().First(p => p.Id == req.Id);
            _mapper.Map(req,info);
            info.ModifyUserId= userId;
            info.ModifyDate= DateTime.Now;
            return await _baseRepository.Db.Updateable(info).ExecuteCommandAsync()>0;
        }

        public async Task<List<MenuRes>> GetMenus(MenuReq req, string userId)
        {
            //查询用户信息，判断是不是超级管理员
            var user = await _baseRepository.Db.Queryable<Users>().FirstAsync(p => p.Id == userId);
            if (user.UserType == 0)
            {
                var list = await _baseRepository.Db.Queryable<Menu>()
                   .WhereIF(!string.IsNullOrEmpty(req.Name), m => m.Name.Contains(req.Name))
                   .WhereIF(!string.IsNullOrEmpty(req.Index), m => m.Index.Contains(req.Index))
                   .WhereIF(!string.IsNullOrEmpty(req.FilePath), m => m.Index.Contains(req.FilePath))
                   .WhereIF(!string.IsNullOrEmpty(req.Description), m => m.Index.Contains(req.Description))
                   .OrderBy((m) => m.Order)
                   .Select(m => new MenuRes() { }, true)
                   .ToTreeAsync(it => it.Children, it => it.ParentId, "");
                return list;
            }
            else
            {
                var list = await _baseRepository.Db.Queryable<Menu>()
                    .InnerJoin<MenuRoleRelation>((m, mrr) => m.Id == mrr.MenuId)
                    .InnerJoin<Role>((m, mrr, r) => r.Id == mrr.RoleId)
                    .InnerJoin<UserRoleRelation>((m, mrr, r, urr) => r.Id == urr.RoleId)
                    .InnerJoin<Users>((m, mrr, r, urr, u) => u.Id == urr.UserId && u.Id == userId)
                    .WhereIF(!string.IsNullOrEmpty(req.Name), m => m.Name.Contains(req.Name))
                    .WhereIF(!string.IsNullOrEmpty(req.Index), m => m.Index.Contains(req.Index))
                    .WhereIF(!string.IsNullOrEmpty(req.FilePath), m => m.Index.Contains(req.FilePath))
                    .WhereIF(!string.IsNullOrEmpty(req.Description), m => m.Index.Contains(req.Description))
                    .OrderBy((m) => m.Order)
                    .Select(m => new MenuRes() { }, true)
                    .ToTreeAsync(it => it.Children, it => it.ParentId, "");
                return list;
            }
        }

        public async Task<bool> SettingMenu(string roleId, string menuId)
        {
            string[] midArr = menuId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            //先删除关系，后批量新增关系
            await _baseRepository.Db.Deleteable<MenuRoleRelation>(s => s.RoleId == roleId).ExecuteCommandAsync();
            var newList = new List<MenuRoleRelation>();
            foreach (var it in midArr)
            {
                newList.Add(new MenuRoleRelation() { Id = Guid.NewGuid().ToString(), RoleId = roleId, MenuId = it });
            }
            return await _baseRepository.Db.Insertable(newList).ExecuteCommandAsync() > 0;
        }
    }
}
